﻿using B.S.BasicData.API.Write.Application.Command.User;
using B.S.BasicData.Domain.Entities.UserRoleMenu;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;
using System.Transactions;

namespace B.S.BasicData.API.Write.Application.Handler.User
{
    /// <summary>
    /// 删除用户信息请求命令处理类
    /// </summary>
    public class DeleteUserHandler:IRequestHandler<DeleteUserCommand,ApiResult<int>>
    {
        IBaseRepository<UserModel> userRep;
        IBaseRepository<UserRoleModel> userRoleRep;

        public DeleteUserHandler(IBaseRepository<UserModel> userRep, IBaseRepository<UserRoleModel> userRoleRep)
        {
            this.userRep = userRep;
            this.userRoleRep = userRoleRep;
        }

        public Task<ApiResult<int>> Handle(DeleteUserCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<int> res = new ApiResult<int>();

                var user = userRep.GetAll().Where(x => x.Id == request.id).FirstOrDefault();
                if (user == null)
                {
                    res.Msg = "用户信息不存在";
                    res.Code=ApiEnum.Fail;
                    return Task.FromResult(res);
                }

                user.IsDeleted = true;
                user.UpdateDate = DateTime.Now;
                user.UpdateName = user.UserName;

                var userroles=userRoleRep.GetAll().Where(x=>x.UserId==user.Id).ToList();
                foreach (var item in userroles)
                {
                    item.IsDeleted = true;
                }

                int r1 = 0;
                int r = 0;

                using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    if (userroles.Count > 0)
                    {
                        r1 = userRoleRep.UpdateAsync(userroles).Result;
                    }
                    r=userRep.UpdateAsync(user).Result;
                    tran.Complete();
                 }


                if (r > 0)
                {
                    res.Msg = "删除用户信息成功";
                    res.Data = r;
                    res.Code = ApiEnum.Success;
                }
                else
                {
                    res.Msg = "删除用户信息失败";
                    res.Code = ApiEnum.Fail;
                }

                return Task.FromResult(res);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
